<template>
	<view class="record-container">
		<view class="" style="z-index: 1000; position: fixed; top: 0; left: 0; right: 0;">
			<view class="" v-show="targets.length>1"
				style="display: flex; justify-content: center; align-items: center; height: 30px; background-color: #F2F2F0;">
				<text>左右滑动切换不同指标页面</text>
			</view>
			<view class=""
				style="display: flex; justify-content: center; align-items: center; background-color: #fff; height: 35px;">
				<text
					style="margin-left: 5px; display: inline-block; display: flex; justify-content: center; align-items: center; height: 30px; width: 30px; border-radius: 50%;"
					v-for=" (item,index1) in targets.length" :key="index1"
					:style="index1 === index ? 'background-color: #3288DF;': 'background-color: #CCCCCC;'">
					{{index1+1}}</text>
			</view>
		</view>
		<view class="" style="background-color: #fff;" :style="{height: (targets.length> 1? '60px': '30px') }">

		</view>
		<swiper class="swiper" :indicator-dots="false" :autoplay="false" duration="500">
			<swiper-item v-for="(target,index) in targets" :key="target.id">
				<wyb-slide-listener @slideLeft="onSlide" @slideRight="onSlide">
					<!-- 此处放你要监听的内容 -->
					<uni-forms :ref="'targetForm'+index" :modelValue="target" label-position="top">
						<uni-forms-item label="指标名称" name="name">
							<uni-easyinput v-model="target.name" disabled />
						</uni-forms-item>
						<uni-forms-item label="活动时间" name="createTime">
							<uni-easyinput v-model="target.createTime" disabled />
						</uni-forms-item>
						<uni-forms-item label="指标说明" name="content">
							<uni-easyinput type="textarea" disabled v-model="target.content" />
						</uni-forms-item>

						<uni-forms-item label="评价结果" name="result">
							<uni-easyinput type="textarea" v-model="target.result" disabled />
						</uni-forms-item>
						<uni-forms-item label="审核评价" name="remark" v-if="target.commentRemark.length>0">
							<uni-list>
								<uni-list-item v-for="(item, index2) in target.commentRemark" :key="index2"
									:title="item.content">
									<template v-slot:body>
										<text class="slot-box slot-text">{{item.content}}</text>
									</template>
									<template v-slot:footer>
										<image class="slot-image" :src="getSrc(item.state)" mode="widthFix"
											style="height: 25px;width: 25px;margin-left: auto;"></image>
									</template>
								</uni-list-item>
							</uni-list>
						</uni-forms-item>
						<view class="" v-show="target.improveState!=1">
							<uni-forms-item label="评价" name="improveT">
								<uni-easyinput type="textarea" v-model="target.improveT" placeholder="请输入评价" />
							</uni-forms-item>
						</view>
					</uni-forms>
				</wyb-slide-listener>

			</swiper-item>
		</swiper>

		<view class="media">
			<button type="primary" class="media-btn" @click="handlerPhoto">拍照</button>
			<button class="media-btn" @click="handlerVoice">录音</button>
			<button class="media-btn" @click="handlerVideo">视频</button>
		</view>
		<view class="mediaView">
			<u-cell-group>
				<u-cell isLink icon="file-text-fill" title="实证资料" @click="viewFile">
					<u-badge slot="value" :showZero="true" :value="fileNum"></u-badge>
				</u-cell>
			</u-cell-group>
		</view>
	</view>
</template>

<script>
	import storage from '@/utils/storage'
	import wybSlideListener from '@/components/wyb-slide-listener/wyb-slide-listener.vue'
	import {
		schoolTarget,
		saveSchoolComment,
		commitSchoolComment
	} from '@/api/school/index.js'
	import {
		deepClone,
		isNotNull
	} from "@/utils/common.js"
	// 引入上传文件接口
	import {
		uploadUrl,
	} from "@/api/supervise/index.js"
	export default {
		data() {
			return {
				activityId: "",
				// 活动指标id
				targetId: "",
				schoolId: "",
				comments: [],
				targets: [],
				index: 0,
				fileNum: 0,
				changeBtnTitleFlag: false,
				uploadUrl
			}
		},
		methods: {
			submit() {
				console.log(this.targets)
				for (let i = 0; i < this.targets.length; i++) {
					// 评价保存在improveT
					if (this.targets[i].improveT === "") {
						uni.$u.toast("评级内容不能为空");
						return false
					}
				}

				if (!this.changeBtnTitleFlag) {
					console.log("准备保存")
					// 当标志为false,表示未提交

					// 保存前上传图片

					let uuid = this.index
					const videoData = this.$store.state.file[`video_files_${uuid}`] || [];
					const imgData = this.$store.state.file[`pic_files_${uuid}`] || [];
					const voiceData = this.$store.state.file[`voice_files_${uuid}`] || [];
					let files = [];
					videoData.forEach(item2 => {
						files.push({
							uri: item2.url
						})
					});
					imgData.forEach(item2 => {
						files.push({
							uri: item2.url
						})
					});
					let commentUrlId
					voiceData.forEach(item2 => {
						files.push({
							uri: item2.url
						})
					});
					console.log(files.length)
					if (files.length > 0) {
						this.uploadFile(files).then(res => {
							commentUrlId = res
							console.log(commentUrlId)
							saveSchoolComment(this.targets[0].commentId, JSON.stringify(commentUrlId), this
									.targets[0].improveT)
								.then(res => {
									console.log(res)
									this.changeNaBtnTitle("提交")
									this.changeBtnTitleFlag = true
								})
						});
					} else {
						saveSchoolComment(this.targets[0].commentId, "", this.targets[0].improveT).then(res => {
							console.log(res)
							this.changeNaBtnTitle("提交")
							this.changeBtnTitleFlag = true
						})
					}


				} else {
					console.log("准备提交")
					commitSchoolComment(this.targets[0].commentId, this.targets[0].improveT, this.targets[0].contentId)
						.then(res => {
							this.changeNaBtnTitle("提交了")
							console.log(res)
						})
				}

			},
			onSlide: function(e) {
				let type = e.type
				switch (type) {
					case 'slideLeft':
						if (this.index < this.targets.length - 1) {
							this.index++;
							this.getFileNum();
						}
						break
					case 'slideRight':
						if (this.index > 0) {
							this.index--;
							this.getFileNum();
						}
						break
				}
			},
			getSchoolTarget(id) {

				schoolTarget(id).then(res => {
					console.log(res)
					let targets = res.targets
					let comments = res.comments
					let firstComments = res.firstComments
					for (let i = 0; i < targets.length; i++) {

						for (let j = 0; j < comments.length; j++) {

							if (comments[j].targetId == targets[i].id) {
								targets[i].commentRemark = comments[j].commentRemark
								targets[i].createTime = comments[j].createTime
								targets[i].improveState = comments[j].improveState
								targets[i].commentId = comments[j].id
								targets[i].improveT = ""
								targets[i].contentId = ""

							}

						}

					}

					for (let k = 0; k < firstComments.length; k++) {
						targets[k].firstComments = firstComments[k]
						targets[k].result = this.getResult(firstComments[k])
					}
					if ('finishRemark' in res) {
						targets[0].improveT = res.finishRemark[0].content
						targets[0].contentId = res.finishRemark[0].id
						this.changeBtnTitleFlag = true
						this.changeNaBtnTitle('提交')
					}

					this.targets = targets;
					console.log(targets)
					this.comments = comments;
					this.comments.forEach(item => {
						item["imgUrls"] = isNotNull(item.imgUrl) ? item.imgUrl.split(",") : [];
						item["voiceUrls"] = isNotNull(item.voiceUrl) ? item.voiceUrl.split(",") : [];
						item["videoUrls"] = isNotNull(item.videoUrl) ? item.videoUrl.split(",") : [];
					})
					this.getFileNum()
				})
			},
			changeNaBtnTitle(text) {
				var pages = getCurrentPages();
				var page = pages[pages.length - 1];
				var currentWebview = page.$getAppWebview();
				var tn = currentWebview.getStyle().titleNView;

				if (text == "提交了") {
					tn.buttons[0].width = 0;
					currentWebview.setStyle({
						titleNView: tn
					});
				} else {
					tn.buttons[0].text = text;
					currentWebview.setStyle({
						titleNView: tn
					});
				}
			},
			getResult(value) {

				let result = "";

				if (value.improveState == 2) {
					result = "不合格";
				} else if (value.improveState == 1) {
					result = "合格";
				}

				if (value.light != null) {
					result = result + "\n亮点：" + value.light
				}

				if (value.content != null) {
					result = result + "\n问题：" + value.content
				}

				return result;

			},
			getSrc(state) {
				if (state == 1) {
					return "/static/images/icon_du_lv.png";
				} else {
					return "/static/images/icon_school_lv.png";
				}
			},
			viewFile() {
				if (this.fileNum == 0) {
					this.$u.toast("暂无实证资料");
					return;
				}
				const comment = this.comments[this.index];
				const fileUrls = {
					imgUrls: comment.imgUrls,
					voiceUrls: comment.voiceUrls,
					videoUrls: comment.videoUrls,
				}
				this.$tab.navigateTo("/pages/empirical-file/empirical-file?fileUrls=" + encodeURIComponent(JSON
					.stringify(fileUrls)));
			},
			getFileNum() {
				let num = 0;
				const comment = this.comments[this.index]
				num += comment.imgUrls.length;
				num += comment.voiceUrls.length;
				num += comment.videoUrls.length;
				this.fileNum = num;
			},
			handlerPhoto() {
				const comment = this.targets[this.index].firstComments;
				const uuid = this.index;
				uni.$u.route('/pages/school-index/media-data/photo-data', {
					uuid,
					imageUrls: JSON.stringify(comment.imgUrl ? comment.imgUrl.split(",") : [])
				});
			},

			handlerVoice() {
				const comment = this.targets[this.index].firstComments;
				const uuid = this.index;
				uni.$u.route('/pages/school-index/media-data/voice-data', {
					uuid,
					voiceUrls: JSON.stringify(comment.voiceUrl ? comment.voiceUrl.split(",") : [])
				});
			},
			handlerVideo() {
				const comment = this.targets[this.index].firstComments;
				const uuid = this.index;
				uni.$u.route('/pages/school-index/media-data/video-data', {
					uuid,
					videoUrls: JSON.stringify(comment.videoUrl ? comment.videoUrl.split(",") : [])
				});
			},
			showFile() {
				return this.targets[this.index]?.isPositive === 1;
			},
			uploadFile(files) {
				const saveFiles = deepClone(files);
				let urlId = [];
				return new Promise((resolve, reject) => {
					console.log("开始上传")
					if (saveFiles) {
						saveFiles.forEach((file, index) => {
							uni.uploadFile({
								url: this.uploadUrl,
								files: [file],
								success: (res) => {
									if (res.statusCode === 200) {
										const resData = JSON.parse(res
											.data);
										urlId = [...urlId,
											...resData.urlId
										];
									} else {
										uni.$u.toast("实证材料上传失败");
										return;
									}
									if (index === saveFiles.length - 1) {
										resolve(urlId);
									}
								},
								fail: (err) => {
									console.log(err)
									uni.$u.toast("实证材料上传失败");
									return;
								}
							})
						});
					} else {
						resolve()
					}
				});
			}

		},
		onLoad: function(option) {
			uni.setNavigationBarTitle({
				title: option.targetName
			});
			this.getSchoolTarget(option.id);
		},
		onNavigationBarButtonTap(e) {

			// 点击导航栏自定义按钮
			this.submit()
		}
	}
</script>

<style lang="scss" scoped>
	.record-container {
		font-size: 20px;

		.swiper {
			width: 100vw;
			min-height: 200vh;
		}



		.title-box {}

		.title-height {
			height: 7vh;
			line-height: 7vh;
			background-color: #F2F2F0;
		}

		.content {
			min-height: 7vh;
			background-color: #fff;
			// padding: 0 12px;
		}

		.pl-12 {
			padding-left: 12px;

		}

		.radio {
			padding-left: 10px;
		}

		.media {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 50px;
			height: 50px;
			display: flex;
			background-color: #fff;
		}

		.mediaView {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			height: 50px;
			display: flex;
			background-color: #fff;

			.media-btn {
				width: 25vw;
			}
		}

	}

	/deep/ .is-disabled {
		background-color: #ffffff !important;
		color: #0d0d0d !important;
	}
</style>